package training.bms.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;

import training.bms.business.Blog;
import training.bms.business.BlogSearchOptions;
import training.bms.business.Blog_;
import training.framework.persistence.AbstractEntityDao;

public class BlogDao extends AbstractEntityDao<Integer, Blog, BlogSearchOptions>{

	public BlogDao() {
		super(EntityManagerFactorySingleton.FACTORY, Blog.class);
	}

	@Override
	protected Order toOrder(CriteriaBuilder builder, Root<Blog> root) {
		
		return builder.asc(root.get(Blog_.name));
	}

	@Override
	protected Predicate toPredicate(CriteriaBuilder builder, Root<Blog> root,
			BlogSearchOptions options) {
		Predicate namePredicate;
		String blogName = options.getName();
		if (StringUtils.isBlank(blogName)) {
			namePredicate = builder.conjunction();								
		} else {
			namePredicate = builder.like(
				builder.lower(root.get(Blog_.name)), 
				toLikeParameter(blogName)
			);
		}
			
		Predicate descriptionPredicate;
		String blogDescription = options.getDescription();
		if (StringUtils.isBlank(blogDescription)) {
			descriptionPredicate = builder.conjunction();
		} else {
			descriptionPredicate = builder.like(
				builder.lower(root.get(Blog_.description)), 
				toLikeParameter(blogDescription)
			);				
		}
		
		Predicate predicate = builder.and(namePredicate, descriptionPredicate);
		return predicate;
	}

	public Blog selectBlog(String blogName) {
		// select from BLO_BLOG as b where trim(lower(BLO_NAME)) = blogName.toLowerCase().trim()		
		// select b from Blog.class.getName() where trim(lower(b.name)) = blogName.toLowerCase().trim()
		// select b from Blog.class.getName() where trim(lower(b.name)) = :blogName
		StringBuilder jpql = new StringBuilder("select b from ");
		jpql.append(Blog.class.getName());
		jpql.append(" b where trim(lower(b.name)) = :blogName");
		EntityManager manager = null;
		try {
			manager =  EntityManagerFactorySingleton.FACTORY.createEntityManager();
			TypedQuery<Blog> query = manager.createQuery(jpql.toString(), Blog.class);
			query.setParameter("blogName", blogName.toLowerCase().trim());
			List<Blog> result = query.getResultList();
			if (result.isEmpty()) {
				return null;
			} else {
				return result.get(0);
			}
		} finally {
			if (manager != null) {
				try {
					manager.close();
				} catch (RuntimeException e) {}
			}
		}				
	}
	
	
}
